package cz.data.domain.market.integration.listener;

import cz.data.domain.market.integration.listener.event.CallDataServiceLogEvent;
import cz.data.domain.market.integration.service.ServiceLogService;
import cz.data.domain.market.model.dto.ServiceLogDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;

@Slf4j
@Component
public class SpringEventListener {

    @Resource
    ThreadPoolTaskExecutor taskExecutor;
    @Autowired
    ServiceLogService serviceLogService;

    @EventListener(CallDataServiceLogEvent.class)
    public void callDataServiceLogEvent(CallDataServiceLogEvent event) {
        ServiceLogDto serviceLogDto = event.getLog();
        CompletableFuture.runAsync(() -> serviceLogService.saveServiceLog(serviceLogDto), taskExecutor)
                .whenCompleteAsync((response, e) -> {
                    if (Objects.nonNull(e)) {
                        log.error(e.getMessage(), e);
                    }
                }, taskExecutor);
    }
}
